<template>
  <div class="app-container">
    <!-- 搜索区域 -->
    <el-form :model="queryParams" inline>
      <el-form-item label="开始时间">
        <el-date-picker
          v-model="queryParams.startTime"
          type="datetime"
          placeholder="选择开始时间"
          style="width: 200px"
          :disabled-date="disableOtherMonths"
        />
      </el-form-item>

      <el-form-item label="结束时间">
        <el-date-picker
          v-model="queryParams.endTime"
          type="datetime"
          placeholder="选择结束时间"
          style="width: 200px"
          :disabled-date="disableOtherMonths"
        />
      </el-form-item>

      <el-form-item label="用户ID">
        <el-input
          v-model="queryParams.userId"
          placeholder="请输入用户ID"
          clearable
          style="width: 200px"
        />
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="getList">查询</el-button>
        <el-button @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 表格 -->
    <el-table :data="tableData" style="width: 100%; margin-top: 10px">
      <el-table-column prop="userId" label="用户ID" />
      <el-table-column prop="beforeScore" label="变动前积分" />
      <el-table-column prop="changeScore" label="变动积分" />
      <el-table-column prop="afterScore" label="变动后积分" />
      <el-table-column prop="changeType" label="变动类型" />
      <el-table-column prop="createTime" label="创建时间" />
      <el-table-column prop="remark" label="备注" />
    </el-table>

    <!-- 分页 -->
    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.page"
      v-model:limit="queryParams.size"
      @pagination="getList"
    />
  </div>
</template>

<script setup>
import { ref, onMounted } from "vue";
import dayjs from "dayjs";
import { ElMessage } from "element-plus";
import { listScoreDetail,listScoreMonth } from "@/api/min-app/score-details";

// ✅ 接口返回允许选择的月份
const availableMonths = ref([]); // 例如 ["202510", "202509", "202508"]

// 获取允许的月份
const getAvailableMonths = async () => {
  try {
    const res = await listScoreMonth(); // 调用 /user/scoredetail/month
    if (res.code === 200) {
      availableMonths.value = res.data || [];
    } else {
      ElMessage.error(res.msg || "获取月份失败");
    }
  } catch (err) {
    console.error(err);
    ElMessage.error("服务器异常，请稍后再试");
  }
};

// ✅ 只允许选择返回月份的日期
const disableOtherMonths = (date) => {
  if (!availableMonths.value.length) return false;
  const formatted = dayjs(date).format("YYYYMM");
  return !availableMonths.value.includes(formatted);
};

// 默认时间范围（当前月）
const getDefaultMonthRange = () => {
  const now = dayjs();
  const start = now.startOf("month").format("YYYY-MM-DD 00:00:00");
  const end = now.format("YYYY-MM-DD HH:mm:ss");
  return { start, end };
};

const { start, end } = getDefaultMonthRange();

// 查询参数
const queryParams = ref({
  page: 1,
  size: 10,
  startTime: start,
  endTime: end,
  userId: "",
});

const tableData = ref([]);
const total = ref(0);

// 查询列表
const getList = async () => {
  try {
    const params = {
      ...queryParams.value,
      startTime: dayjs(queryParams.value.startTime).format("YYYY-MM-DD HH:mm:ss"),
      endTime: dayjs(queryParams.value.endTime).format("YYYY-MM-DD HH:mm:ss"),
       userId: queryParams.value.userId || "-1",
    };

    const res = await listScoreDetail(params);
    if (res.code === 200) {
      console.log('接口返回 total:', res.data);

      tableData.value = res.data.records;
      total.value = Number(res.data.total) || 0;
    } else {
      ElMessage.error(res.msg || "查询失败");
    }
  } catch (err) {
    console.error("请求失败:", err);
    ElMessage.error("服务器异常，请稍后再试");
  }
};

// 重置查询条件
const resetQuery = () => {
  const { start, end } = getDefaultMonthRange();
  queryParams.value = {
    page: 1,
    size: 10,
    startTime: start,
    endTime: end,
    userId: "",
  };
  getList();
};

// 页面加载
onMounted(async () => {
  await getAvailableMonths();
  getList();
});
</script>
